package com.sport.service;

import com.sport.constant.MessageConstant;
import com.sport.context.BaseContext;
import com.sport.exception.BaseException;
import com.sport.exception.KickException;
import com.sport.exception.RoomFullException;
import com.sport.mapper.RoomMapper;
import com.sport.pojo.dto.CampMessageDto;
import com.sport.pojo.dto.GameResults;
import com.sport.pojo.dto.RoomDto;
import com.sport.pojo.dto.UserListDto;
import com.sport.pojo.entity.Room;
import com.sport.pojo.vo.RoomStatusVo;
import com.sport.pojo.vo.RoomVo;
import com.sport.pojo.entity.UandR;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.locks.Lock;

import static com.sport.constant.CampConstant.RED;
import static com.sport.constant.MessageConstant.BLUE_ROOM_COUNT_FULL;
import static com.sport.constant.MessageConstant.RED_ROOM_COUNT_FULL;

@Service
public class RoomServiceImpl implements RoomService {
    @Autowired
    private RoomMapper roomMapper;
    @Autowired
    private Lock lock;

    @Override
    public List<RoomVo> findRoom(String currentAccount) {
        List<RoomVo> room = roomMapper.findRoom(currentAccount);
        return room;
    }

    public int createRoom(RoomDto roomDto) {
        roomDto.setRoomId(UUID.randomUUID().toString());
        Room room = new Room();
        BeanUtils.copyProperties(roomDto, room);
        room.setRoomhostId(BaseContext.getCurrentId());
        room.setCreateTime(LocalDateTime.now());
        //自动添加创建房间房主信息到ur中间表，默认房主加入0 红色方
        UandR uandR = new UandR();
        uandR.setUserId(room.getRoomhostId());
        uandR.setRoomId(room.getRoomId());
        uandR.setCamp(0);
        //排位模式默认房主位置
        uandR.setImgId(2131361893);
        roomMapper.userIntoRoom(uandR);
        return roomMapper.createRoom(room);
    }

    @Override
    public int userIntoRoom(UandR uandR) {
        lock.lock();
        try {
            if (roomMapper.campNum(uandR) == roomMapper.getMaxNum(uandR) / 2) {
                if (uandR.getCamp() == RED) {
                    throw new RoomFullException(RED_ROOM_COUNT_FULL);
                } else {
                    throw new RoomFullException(BLUE_ROOM_COUNT_FULL);
                }
            }
            int info = roomMapper.userIntoRoom(uandR);
            int info2 = roomMapper.addCurrentCount(uandR.getRoomId());
            if(info==0 || info2==0){
                return 0;
            }
           if(roomMapper.isFull(uandR)==1){
               roomMapper.updateRoomStatus(uandR);
               return 2;
           }else {
               return 1;
           }
        }finally {
            lock.unlock();
        }

    }

    @Override
    public int userChangeCamp(UandR uandR) {
        lock.lock();
        try {
            if (roomMapper.campNum(uandR) == roomMapper.getMaxNum(uandR) / 2) {
                if (uandR.getCamp() == RED) {
                    throw new RoomFullException(RED_ROOM_COUNT_FULL);
                } else {
                    throw new RoomFullException(BLUE_ROOM_COUNT_FULL);
                }
            }
            return roomMapper.userChangeCamp(uandR);
        }finally {
            lock.unlock();
        }

    }

    @Override
    public RoomVo findRoomByUserId(String userId) {
        RoomVo roomVo = roomMapper.selectRoomById(userId);
        return roomVo;
    }

    public CampMessageDto showRoomNumber(String roomId) {
        List<UserListDto> templist = roomMapper.showRoomNumber(roomId);
        List<UserListDto> redRoomMembers = new ArrayList<>();
        List<UserListDto> blueRoomMembers = new ArrayList<>();
        UserListDto judge = null;
        for (UserListDto userListDto : templist) {
            if (userListDto.getCamp() == 0) {
                redRoomMembers.add(userListDto);
            } else if(userListDto.getCamp() == 1) {
                blueRoomMembers.add(userListDto);
            }else if(userListDto.getCamp()==2){
                judge=userListDto;
            }
        }
        CampMessageDto campMessageDto = new CampMessageDto();
        campMessageDto.setRedRoomMembers(redRoomMembers);
        campMessageDto.setBlueRoomMembers(blueRoomMembers);
        campMessageDto.setRoomTrail(judge);
        return campMessageDto;
    }

    @Override
    public int exitRoom(UandR uandR) {
        roomMapper.reduceCount(uandR);
        return roomMapper.exitRoom(uandR);
    }

    @Override
    public int trailSubmitResults(GameResults gameResults) {
        return roomMapper.trailSubmitResults(gameResults);
    }

    @Override
    @Transactional
    public int destroyRoom(UandR uandR) {
       int info1 =  roomMapper.deleteUandRByRoomId(uandR.getRoomId());
        int info2 = roomMapper.deleteRoomByUserId(uandR.getUserId());
        if(info1!=0&&info2!=0){
            return 1;
        }
       return 0;
    }

    @Override
    public int kickUser(UandR uandR) {
        roomMapper.reduceCount(uandR);
        return roomMapper.kickUser(uandR);
    }

    @Override
    public List<RoomVo> findNormalRoom(String currentId) {
        List<RoomVo> room = roomMapper.findNormalRoom(currentId);
        return room;
    }


    @Override
    public int trailBeginGame(String roomId) {
        return roomMapper.trailBeginGame(roomId);
    }

    @Override
    public int startGame(String roomId, String place) {
        return roomMapper.startGame(roomId,place,LocalDateTime.now());
    }

    @Override
    public int endGame(String roomId) {
        return roomMapper.endGame(roomId,LocalDateTime.now());
    }

    @Override
    public RoomStatusVo findRoomStatusByRoomId(String roomId) {
        if(roomMapper.findRoomStatusByRoomId(roomId)==null){
            throw new BaseException("无此房间");
        }
        //判断你是否被踢出
        if (roomMapper.isKickUser(roomId, BaseContext.getCurrentId())==0) {
            throw new KickException(MessageConstant.KICK_USER);
        }
        return roomMapper.findRoomStatusByRoomId(roomId);
    }

    @Override
    public List<RoomVo> searchRoom(String roomHostName,String type) {
        List<RoomVo> list = null;
        if(type.equals("0")){
            list =  roomMapper.searchRoom(roomHostName,0);
        }else if(type.equals("1")){
            list =  roomMapper.searchRoom(roomHostName,1);
        }
        if(list==null || list.size()==0){
            throw new BaseException("无此房间");
        }
        return list;
    }
}
